<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla modelitem library
jimport('joomla.application.component.modeladmin');

/**
 * Model
 */
abstract class MariagePlannerBaseModelAdmin extends JModelAdmin
{	
	protected function loadFormData()
	{
		$data = $this->getItem();
		return $data;
	}
	
	public function getOwnerItemIds() {
		$user = JFactory::getUser();
		$db = JFactory::getDbo();

		$query = $db->getQuery(true);
		$query->select('tbl.id as id');
		$query->from('#__mariageplanner_user_lnk as lnk');
		$query->innerJoin("#__mariageplanner_{$this->_table_name} as tbl ON tbl.planner_id=lnk.planner_id");
		$query->where('lnk.uid=' . (int)$user->id);
		$db->setQuery($query);
		$data = $db->loadColumn();
		return $data;
	}
	
	public function getOwnerId()
	{
		$db = JFactory::getDbo();
		
		$query = $db->getQuery(true);
		$query->select('lnk.uid as id');
		$query->from('#__mariageplanner_user_lnk as lnk');
		$query->innerJoin("#__mariageplanner_{$this->_table_name} as t ON t.planner_id=lnk.planner_id");
		$query->where('t.id=' . (int)$this->getState('item.id'));
		$db->setQuery($query);
		$data = $db->loadObject();
        $id = (int)$data->id;
		return $id;
	}
	
	public function isOwner() 
	{
        if((int)$this->getState('item.id')==0)
            return true;

		$user = JFactory::getUser();
		$ownerId = (int)$this->getOwnerId();
		return (int)$user->id === $ownerId;
	}
	
	protected function _canEdit($record)
	{
		if($this->isOwner())
			return true;
		$user = JFactory::getUser();		
		return $user->authorise('core.edit', $this->option);
	}
	
	public function save($data)
	{
		if(!$this->_canEdit(null)) {
			$this->setError(JText::_('JLIB_APPLICATION_ERROR_SAVE_NOT_PERMITTED'));
			return false;
		} else {
			if(empty($data['planner_id']))
				$data['planner_id'] = $this->getState('planner.id');
			return parent::save($data);
		}
	}
	
	protected function canDelete($record)
	{		
		if($this->isOwner())
			return true;
		return parent::canDelete($record);
	}
	
	protected function canEditState($record)
	{
		if($this->isOwner())
			return true;
		return parent::canEditState($record);
	}
	
	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since	1.6
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication();
		
		$pk = JRequest::getInt('id');
		$this->setState('item.id', $pk);

		$pid = _getDefaultPlannerId($this->getDbo());
		$this->setState('planner.id', $pid);
		
        // Load the parameters.
		$params = $app->getParams();
		$this->setState('params', $params);
		
		parent::populateState();
	}
}
?>
